let winston = require ('winston');
let path = require ('path');
require ('winston-daily-rotate-file');
//require('./MysqlLogger');//把日志写进数据库，现在不需要
winston.remove (winston.transports.Console);
let metaFormat = function ( meta )
{
    let str = "";
    str += meta.location + " ";
    delete meta.date;
    delete meta.location;
    let message = meta.message;
    if (typeof message === 'string' && meta.method == undefined)
    {
        str += "[" + message + "]";
    }
    else if (typeof message === 'object' && meta.method == undefined)
    {
        delete message.date;
        for (let key in message)
        {
            str += "[" + key + ":" + message[ key ] + "]";
        }
    }
    else if (meta.method != undefined)
    {
        for (let key in meta)
        {
            str += "[" + key + ":" + meta[ key ] + "]";
        }
    }
    return str;
};
let formatter = function ( args )
{
    let date    = (new Date ()).format ('yyyy-MM-dd HH:mm:ss'),
        level   = args.level,
        message = args.message,
        meta    = args.meta;
    return date + " " + level.toUpperCase () + " " + metaFormat (meta);
};
winston.add (winston.transports.Console, {
    formatter: formatter
});
winston.add (winston.transports.DailyRotateFile, {
    name       : 'file',
    datePattern: '.yyyy-MM-dd',
    formatter  : formatter,
    filename   : path.join ("logs", "server"),
    json       : false
});
//winston.add(winston.transports.MysqlLogger);
let logger      = winston,
    requestData = require ('./RequestData');
module.exports.log = function ( message )
{
    log ("info", _getCallerFile (), message);
};
module.exports.info = function ( message )
{
    log ("info", _getCallerFile (), message);
};
module.exports.error = function ( message )
{
    log ("error", _getCallerFile (), message);
};
module.exports.warn = function ( message )
{
    log ("warn", _getCallerFile (), message);
};
function log( level, location, message )
{
    if (message.hasOwnProperty ('originalUrl'))
    {
        //message 是 request 对象
        message = requestData.getData (message);
    }
    logger.log (level, {
        location: location,
        message : message
    });
}
function _getCallerFile()
{
    try
    {
        let err = new Error ();
        let callerfile;
        let currentfile;
        Error.prepareStackTrace = function ( err, stack )
        {
            return stack;
        };
        currentfile = err.stack.shift ().getFileName ();
        while (err.stack.length)
        {
            callerfile = err.stack.shift ().getFileName ();
            if (currentfile !== callerfile)
            {
                return callerfile.slice (callerfile.lastIndexOf ("\\") + 1);
            }
        }
    } catch (err)
    {
    }
    return undefined;
}
module.exports.winston = winston;
Date.prototype.format = function ( format )
{
    let o = {
        "M+": this.getMonth () + 1, //month
        "d+": this.getDate (), //day
        "H+": this.getHours (), //hour
        "m+": this.getMinutes (), //minute
        "s+": this.getSeconds (), //second
        "q+": Math.floor ((this.getMonth () + 3) / 3), //quarter
        "S" : this.getMilliseconds () //millisecond
    };
    if (/(y+)/.test (format))
    {
        format = format.replace (RegExp.$1,
            (this.getFullYear () + "").substr (4 - RegExp.$1.length));
    }
    for (let k in o)
        if (new RegExp ("(" + k + ")").test (format))
        {
            format = format.replace (RegExp.$1,
                RegExp.$1.length == 1 ? o[ k ] :
                    ("00" + o[ k ]).substr (("" + o[ k ]).length));
        }
    return format;
};
